package fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.qianfeng.lingshijia.R;
import com.qianfeng.lingshijia.WebViewActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import adapter.SchoolMarketSingleAdapter;
import entity.SchoolMarketEntity;
import entity.SchoolMarketHeadEntity;
import listener.OnPopupMenuClickListener;
import listener.OnSchoolMarketItemSelectListener;
import utils.Constants;
import utils.DownloadUtils;

public class SchoolMarketFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener {

    private ListView lvSchoolMarket;
    private RadioGroup rgMarketType;
    private int currentSchoolId = 2;//当前加载数据学校ID
    private TextView tvUniversity;
    private ImageView ivSchoolMarketHead;
    private String subLoadDataString;//保存URL的字段在加载数据时一定记得设置他
    private LinearLayout lSchoolMarketHead;
    private LinearLayout rlNotDataView;
    private TextView tvMarketNumber;
    private List<Integer> marketIdList = new ArrayList<Integer>();

    public ListView getLvSchoolMarket() {
        return lvSchoolMarket;
    }

    public RadioGroup getRgMarketType() {
        return rgMarketType;
    }

    public void setSubLoadDataString(String subLoadDataString) {
        this.subLoadDataString = subLoadDataString;
    }

    public String getSubLoadDataString() {
        return subLoadDataString;
    }

    public SchoolMarketFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_market, container, false);
    }

    @Override
    public void init(View view) {
        lvSchoolMarket = (ListView) view.findViewById(R.id.lvSchoolMarket);
        lvSchoolMarket.setOnItemClickListener(new OnSchoolMarketItemSelectListener(marketIdList,getActivity()));

        rgMarketType = (RadioGroup) view.findViewById(R.id.rgMarketType);
        rgMarketType.setOnCheckedChangeListener(this);

        //注册优惠活动的点击事件
        RadioButton rb = (RadioButton) rgMarketType.findViewById(R.id.rbDiscount);
        rb.setOnClickListener(new OnPopupMenuClickListener(this));

        tvUniversity = (TextView) view.findViewById(R.id.tvUniversity);
        tvUniversity.setText("中国计量大学");
        ivSchoolMarketHead = (ImageView) view.findViewById(R.id.ivSchoolMarketHead);
        lSchoolMarketHead = (LinearLayout) view.findViewById(R.id.lSchoolMarketHead);
        rlNotDataView = (LinearLayout) view.findViewById(R.id.rlNotDataView);
        tvMarketNumber = (TextView) view.findViewById(R.id.tvMarketNumber);

        //把数据显示页面的隐藏
        lvSchoolMarket.setVisibility(View.GONE);
        lSchoolMarketHead.setVisibility(View.GONE);

        //把申请店长页面隐藏
        rlNotDataView.setVisibility(View.GONE);
    }

    @Override
    public void loadDatas() {
        rgMarketType.getChildAt(0).performClick();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rbTop:
                subLoadDataString = "orderBy=default&universityNo=";
                loadJson(subLoadDataString);
                break;
            case R.id.rbDiscount:
                break;
            case R.id.rbFast:
                subLoadDataString = "lat=40.049317&lng=116.296499&orderBy=distance&universityNo=";
                loadJson(subLoadDataString);
                break;
        }
    }

    /**
     * 设置加载的学校ID和学校名字同时加载数据
     */
    public void setSchoolNameIdAndLoadDatas(String schoolName, int schoolId) {
        currentSchoolId = schoolId;
        tvUniversity.setText(schoolName);
        RadioButton rb = (RadioButton) rgMarketType.getChildAt(0);
        if (rb.isChecked()) {
            loadJson(subLoadDataString);
        } else {
            rb.performClick();
        }
    }

    /**
     * 加载头部数据的方法，需要设置currentSchoolId作为学校id
     */
    private void loadHeadViewData() {
        DownloadUtils.getJson(Constants.URL.SCHOOL_SELECTED_URL + currentSchoolId, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                final SchoolMarketHeadEntity smhEntity = new Gson().fromJson(responseInfo.result, SchoolMarketHeadEntity.class);
                //把图片设置为空，加载图片，设置点击事件
                ivSchoolMarketHead.setImageBitmap(null);
                DownloadUtils.LoadPicture(smhEntity.getData().getImgUrl(), ivSchoolMarketHead);
                ivSchoolMarketHead.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转到webView布局
                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra("url",smhEntity.getData().getLink());
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(getActivity(), "亲，数据加载失败了，请重试。", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 加载店铺列表的数据并设置
     *
     * @param s 地址URl片段存储在subLoadDataString中
     */
    public void loadJson(String s) {
        String path = Constants.URL.SCHOOL_MARKET_URL + s + currentSchoolId;

        //清空列表店铺id list 数据
        marketIdList.clear();
        DownloadUtils.getJson(path, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                //把数据显示页面的隐藏
                lvSchoolMarket.setVisibility(View.GONE);
                lSchoolMarketHead.setVisibility(View.GONE);

                //把申请店长页面隐藏
                rlNotDataView.setVisibility(View.GONE);

                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    //如果加载的数据不为空才加载头部图片
                    if (jsonObject.getJSONArray("data").length() != 0) {
                        //设置找到的店铺数量
                        tvMarketNumber.setText("你所在的学校找到了" + jsonObject.getJSONArray("data").length() + "位校园店长");

                        SchoolMarketEntity smEntity = new Gson().fromJson(responseInfo.result, SchoolMarketEntity.class);
                        //显示数据显示页面
                        lvSchoolMarket.setVisibility(View.VISIBLE);
                        lSchoolMarketHead.setVisibility(View.VISIBLE);

                        //加载数据头部信息
                        loadHeadViewData();

                        //获取学校超市店铺的id
                        for (int i = 0;i<smEntity.getData().size();i++){
                            marketIdList.add(smEntity.getData().get(i).getId());
                        }

                        //设置ListView店铺列表的数据
                        lvSchoolMarket.setAdapter(new SchoolMarketSingleAdapter(getActivity(), smEntity.getData()) {
                        });
                    } else {
                        //加载的数据为空，显示申请店长的页面
                        rlNotDataView.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(getActivity(), "亲，数据加载失败了，请重试。", Toast.LENGTH_LONG).show();
            }
        });
    }
}
